package com.atguigu.edu.service.impl;

import com.atguigu.commonUtils.R;
import com.atguigu.edu.entity.Course;
import com.atguigu.edu.entity.CourseDescription;
import com.atguigu.edu.entity.Teacher;
import com.atguigu.edu.entity.frontVo.CourseFrontVo;
import com.atguigu.edu.entity.frontVo.CourseWebVo;
import com.atguigu.edu.entity.vo.CourseInfoVo;
import com.atguigu.edu.entity.vo.CoursePublishVo;
import com.atguigu.edu.entity.vo.CourseQuery;
import com.atguigu.edu.mapper.CourseMapper;
import com.atguigu.edu.service.ChapterService;
import com.atguigu.edu.service.CourseDescriptionService;
import com.atguigu.edu.service.CourseService;
import com.atguigu.edu.service.VideoService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author Rayyy666
 * @since 2022-04-02
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {

    @Autowired
    private CourseDescriptionService descriptionService;

    @Autowired
    private VideoService videoService;

    @Autowired //自动注入
    private ChapterService chapterService;

    /**
     * 添加课程的基本信息
     *
     * @param courseInfoVo
     * @return
     */
    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {

        // 1.向课程表 里边添加课程的基本信息
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoVo, course);
        int insert = baseMapper.insert(course);

        if (insert == 0) {
            //添加失败
            throw new GuliException(20001, "添加课程信息失败");
        }

        String courseId = course.getId();

        // 2.向课程简介表 里面添加课程的简介
        CourseDescription description = new CourseDescription();
        description.setDescription(courseInfoVo.getDescription());
        //手动设置课程描述的id 和课程的id保持一对一的关系
        description.setId(courseId);
        descriptionService.save(description);
        return courseId;
    }

    /**
     * 根据课程的ID查询课程的基本信息
     *
     * @param courseId
     * @return
     */
    @Override
    public CourseInfoVo getCourseInfo(String courseId) {

        //1.查询 课程表
        Course course = baseMapper.selectById(courseId);

        CourseInfoVo courseInfoVo = new CourseInfoVo();
        BeanUtils.copyProperties(course, courseInfoVo);

        //2.查询课程描述表
        CourseDescription courseDescription = descriptionService.getById(courseId);

        courseInfoVo.setDescription(courseDescription.getDescription());

        return courseInfoVo;
    }

    /**
     * 修改课程的信息
     *
     * @param courseInfoVo
     */
    @Override
    public void updateCourseInfo(CourseInfoVo courseInfoVo) {
        //1.修改课程表
        Course course = new Course();
        BeanUtils.copyProperties(courseInfoVo, course);
        int update = baseMapper.updateById(course);
        if (update == 0) {
            throw new GuliException(20001, "修改课程信息失败");
        }

        //2.修改课程描述表
        CourseDescription courseDescription = new CourseDescription();
        courseDescription.setId(courseInfoVo.getId());
        courseDescription.setDescription(courseInfoVo.getDescription());
        descriptionService.updateById(courseDescription);
    }

    /**
     * 根据课程的ID查询课程的确认信息
     *
     * @param courseId
     * @return
     */
    @Override
    public CoursePublishVo publishCourseInfo(String courseId) {

        CoursePublishVo publishCourseInfo = baseMapper.getPublishCourseInfo(courseId);

        return publishCourseInfo;
    }

    /**
     * 带分页的条件查询 课程列表
     *
     * @param current
     * @param limit
     * @param courseQuery
     * @return
     */
    @Override
    public Page<Course> pageCourseCondition(long current, long limit, CourseQuery courseQuery) {

        Page<Course> coursePage = new Page<>(current, limit);

        QueryWrapper<Course> wrapper = new QueryWrapper<>();

        //多条件组合查询 判断条件是否为空 如果不为空则拼接条件

        String title = courseQuery.getTitle();
        Integer status = courseQuery.getStatus();
        BigDecimal beginPrice = courseQuery.getBeginPrice();
        BigDecimal endPrice = courseQuery.getEndPrice();
        String begin = courseQuery.getBegin();
        String end = courseQuery.getEnd();
        String teacherId = courseQuery.getTeacherId();
        String id = courseQuery.getId();

        if (!StringUtils.isEmpty(title)) {
            wrapper.like("title", title);
        }
        if (!StringUtils.isEmpty(teacherId)) {
            wrapper.eq("teacher_id", teacherId);
        }
        if (!StringUtils.isEmpty(status)) {
            if (status == 0) {
                wrapper.eq("status", "Draft");
            }
            if (status == 1) {
                wrapper.eq("status", "Normal");
            }
        }
        if (!StringUtils.isEmpty(id)) {
            wrapper.eq("id", id);
        }
        if (!StringUtils.isEmpty(beginPrice)) {
            //ge 大于等于 起始价
            wrapper.ge("price", beginPrice);
        }
        if (!StringUtils.isEmpty(endPrice)) {
            //小于等于 最高价
            wrapper.le("price", endPrice);
        }
        if (!StringUtils.isEmpty(begin)) {
            //大于等于 创建时间
            wrapper.ge("gmt_create", begin);
        }
        if (!StringUtils.isEmpty(end)) {
            //小于等于 修改时间
            wrapper.le("gmt_create", end);
        }

        //按创建时间 降序排序
        wrapper.orderByDesc("gmt_create");

        baseMapper.selectPage(coursePage, wrapper);

        return coursePage;
    }


    /**
     * 根据 课程ID 删除课程
     *
     * @param courseId
     * @return
     */
    @Transactional
    @Override
    public R removeCourseById(String courseId) {
        //1.根据课程ID 删除课程小节
        videoService.removeVideoByCourseId(courseId);

        //2。根据课程ID 删除章节
        chapterService.removeChapterByCourseId(courseId);

        //3.根据课程ID 删除 描述 描述ID就是课程ID
        descriptionService.removeById(courseId);

        //4.删除课程本身
        int result = baseMapper.deleteById(courseId);

        if (result == 0) {
            //删除失败 返回
            throw new GuliException(20001, "删除失败");
        }

        return R.ok();
    }

    /**
     * 带分页的条件查询课程信息
     *
     * @param pageCourse
     * @param courseFrontVo
     * @return
     */
    @Override
    public Map<String, Object> getCourseFrontList(Page<Course> pageCourse, CourseFrontVo courseFrontVo) {

        QueryWrapper<Course> wrapper = new QueryWrapper<Course>();
        //判断条件值是否为空，如果不为空就拼接条件
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectParentId())) {
            //一级分类
            wrapper.eq("subject_parent_id", courseFrontVo.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getSubjectId())) {
            //二级分类
            wrapper.eq("subject_id", courseFrontVo.getSubjectId());
        }
        if (!StringUtils.isEmpty(courseFrontVo.getBuyCountSort())) {
            //购买数量
            wrapper.orderByDesc("buy_count");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getGmtCreateSort())) {
            //创建时间
            wrapper.orderByDesc("gmt_create");
        }
        if (!StringUtils.isEmpty(courseFrontVo.getPriceSort())) {
            //价格
            wrapper.orderByDesc("price");
        }

        baseMapper.selectPage(pageCourse, wrapper);

        List<Course> records = pageCourse.getRecords();
        long current = pageCourse.getCurrent();
        long pages = pageCourse.getPages();
        long size = pageCourse.getSize();
        long total = pageCourse.getTotal();

        boolean hasNext = pageCourse.hasNext();//下一页
        boolean hasPrevious = pageCourse.hasPrevious();//上一页

        HashMap<String, Object> map = new HashMap<>();

        map.put("items", records);
        map.put("current", current);
        map.put("pages", pages);
        map.put("size", size);
        map.put("total", total);
        map.put("hasNext", hasNext);
        map.put("hasPrevious", hasPrevious);

        //map返回
        return map;
    }

    /**
     * 查询页面课程详情的方法
     *
     * @param courseId
     * @return
     */
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {
        return baseMapper.getBaseCourseInfo(courseId);
    }

}
